package cn.itsource.pethome.Basic.controller;

import cn.itsource.pethome.Basic.util.AjaxResult;
import cn.itsource.pethome.Basic.util.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file) throws IOException {
        //获取文件名
        try {
            String filename = file.getOriginalFilename();
            //获取后缀
            String subffix = FilenameUtils.getExtension(filename);
            //开始上传，返回路径
            String upload = FastDfsApiOpr.upload(file.getBytes(), subffix);
            return new AjaxResult().setResult(upload);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败"+e.getMessage());
        }
    }
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String,String> param)throws IOException{
        //获取文件名
        try {
            System.out.println(param);
            //获取url
            String url = param.get("url");
            //截掉第一个/(/group1/M00/00/77/wKgABF89BOmAazIMAADaSryx6i4701.png)
            String rl = url.substring(1);
            //截取组名 group1
            String groupPath = rl.substring(0, rl.indexOf("/"));
            //截取文件名
            String fileName = rl.substring(rl.indexOf("/") + 1);
            //删除图片
            FastDfsApiOpr.delete(groupPath,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败"+e.getMessage());
        }
    }
}
